//
//  MHAsiNetworkItem.m
//  MHProject
//
//  Created by MengHuan on 15/4/23.
//  Copyright (c) 2015年 Sunny. All rights reserved.
//

#import "SMAFNetworkItem.h"
#import "MBProgressHUD+Add.h"

@interface SMAFNetworkItem ()

@end

@implementation SMAFNetworkItem

#pragma mark - 创建一个网络请求项，开始请求网络
/**
 *  创建一个网络请求项，开始请求网络
 *
 *  @param networkType  网络请求方式
 *  @param url          网络请求URL
 *  @param params       网络请求参数
 *  @param delegate     网络请求的委托，如果没有取消网络请求的需求，可传nil
 *  @param hashValue    网络请求的委托delegate的唯一标示
 *  @param showHUD      是否显示HUD
 *  @param successBlock 请求成功后的block
 *  @param failureBlock 请求失败后的block
 *
 *  @return MHAsiNetworkItem对象
 */

- (instancetype)initWithtype:(SMAFNetWorkType)networkType
                               url:(NSString *)url
                            params:(NSDictionary *)params
                          delegate:(id)delegate
                            target:(id)target
                            action:(SEL)action
                         hashValue:(NSUInteger)hashValue
                           showHUD:(BOOL)showHUD
                      successBlock:(SMAFSuccessBlock)successBlock
                      failureBlock:(SMAFFailureBlock)failureBlock
{
    if (self = [super init])
    {
        self.networkType    = networkType;
        self.url            = url;
        self.params         = params;
        self.delegate       = delegate;
        self.showHUD        = showHUD;
        self.tagrget        = target;
        self.select         = action;
        if (showHUD==YES) {
             [MBProgressHUD showActiveMessageNew:@"正在加载数据..." withBackground:YES];
        }
        __weak typeof(self)weakSelf = self;
        ITTDPRINT(@"--请求url地址--%@\n",url);
        ITTDPRINT(@"----请求参数%@\n",params);
        
        switch (networkType) {
            case SMAFNetWorkGET:
            {
                
                _currentTask = [[SMAFNetworkHandler sharedInstance].sessionManager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    [MBProgressHUD dismissHUD];
                    
                    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
                    response.resultDic = responseObject;
                    response.resultCode = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                    ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
                    if (successBlock) {
                        successBlock(task,response);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestDidFinishLoading:)]) {
                        [weakSelf.delegate requestDidFinishLoading:responseObject];
                    }
                    [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:responseObject withObject:nil];
                    [weakSelf removewItem];
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    [MBProgressHUD dismissHUD];
                    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
                    
                    if (error.userInfo[@"NSLocalizedDescription"] == NULL)
                    {
                        response.errorMessage = @"请求错误";
                    } else
                    {
                        response.errorMessage = error.userInfo[@"NSLocalizedDescription"];
                    }
                    ITTDPRINT(@"---error==%@\n",error.localizedDescription);
                    if (failureBlock) {
                        failureBlock(task,response,error);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestdidFailWithError:)]) {
                        [weakSelf.delegate requestdidFailWithError:error];
                    }
                    [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:nil withObject:error];
                    [weakSelf removewItem];
                }];
            
            }
                break;
            case SMAFNetWorkPOST:
            {
                _currentTask = [[SMAFNetworkHandler sharedInstance].sessionManager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    [MBProgressHUD dismissHUD];
                    
                    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
                    response.resultDic = responseObject;
                    response.resultCode = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                    ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
                    if (successBlock) {
                        successBlock(task,response);
                    }
                    ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
                    if (successBlock) {
                        successBlock(task, response);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestDidFinishLoading:)]) {
                        [weakSelf.delegate requestDidFinishLoading:responseObject];
                    }
                    [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:responseObject withObject:nil];
                    [weakSelf removewItem];
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    [MBProgressHUD dismissHUD];
                    
                    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
                    
                    if (error.userInfo[@"NSLocalizedDescription"] == NULL)
                    {
                        response.errorMessage = @"请求错误";
                    } else
                    {
                        response.errorMessage = error.userInfo[@"NSLocalizedDescription"];
                    }
                    
                    ITTDPRINT(@"---error==%@\n",error.localizedDescription);
                    if (failureBlock) {
                        failureBlock(task, response ,error);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestdidFailWithError:)]) {
                        [weakSelf.delegate requestdidFailWithError:error];
                    }
                    [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:nil withObject:error];
                    [weakSelf removewItem];
                    
                }];
            }
                break;
            case SMAFNetWorkPATCH:
            {
                _currentTask = [[SMAFNetworkHandler sharedInstance].sessionManager PATCH:url parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    [MBProgressHUD dismissHUD];
                    
                    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
                    response.resultDic = responseObject;
                    response.resultCode = [NSString stringWithFormat:@"%@",responseObject[@"result"]];
                    ITTDPRINT(@"\n\n----请求的返回结果 %@\n",responseObject);
                    if (successBlock) {
                        successBlock(task, response);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestDidFinishLoading:)]) {
                        [weakSelf.delegate requestDidFinishLoading:responseObject];
                    }
                    [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:responseObject withObject:nil];
                    [weakSelf removewItem];
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                    [MBProgressHUD dismissHUD];
                    
                    SMAFNetworkResponse *response = [SMAFNetworkResponse getResponse];
                    
                    if (error.userInfo[@"NSLocalizedDescription"] == NULL)
                    {
                        response.errorMessage = @"请求错误";
                    } else
                    {
                        response.errorMessage = error.userInfo[@"NSLocalizedDescription"];
                    }
                    ITTDPRINT(@"---error==%@\n",error.localizedDescription);
                    if (failureBlock) {
                        failureBlock(task, response , error);
                    }
                    if ([weakSelf.delegate respondsToSelector:@selector(requestdidFailWithError:)]) {
                        [weakSelf.delegate requestdidFailWithError:error];
                    }
                    [weakSelf performSelector:@selector(finishedRequest: didFaild:) withObject:nil withObject:error];
                    [weakSelf removewItem];
                    
                }];
            }
                break;
            default:
                break;
        }
    }
    return self;
}
/**
 *   移除网络请求项
 */
- (void)removewItem
{
    __weak typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([weakSelf.delegate respondsToSelector:@selector(netWorkWillDealloc:)]) {
            [weakSelf.delegate netWorkWillDealloc:weakSelf];
        }
    });
}

- (void)finishedRequest:(id)data didFaild:(NSError*)error
{
    if ([self.tagrget respondsToSelector:self.select]) {
        [self.tagrget performSelector:@selector(finishedRequest:didFaild:) withObject:data withObject:error];
    }
}


@end
